package com.fit.utils.se;


/**
 * 编码工具
 * @author hcl
 *
 */
public class CodingUtil {
	
	
	/**
	 * 判断一个char是否是一个中文
	 * @param c
	 * @return
	 * @author hcl
	 */
	public static boolean isChinese(char c) {
		if(c == 43){//'+'号转义
			return true;
		}
        return c >= 0x4E00 &&  c <= 0x9FA5;// 根据字节码判断
    }
	
	/**
	 * 只将中文Unicode编码
	 * @param str
	 * @return
	 * @author hcl
	 */
	public static String encryptUnicodeByChinese(String str) {
		if(str == null)return null;
		if("".equals(str.trim())) return "";
        char[] utfBytes = str.toCharArray();
        StringBuilder unicodeBytes = new StringBuilder();
        for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
        	String s = null;
        	if(isChinese(utfBytes[byteIndex])){
        		s = encryptUnicode(utfBytes[byteIndex]);
        	}else{
        		s = utfBytes[byteIndex]+"";
        	}
            unicodeBytes.append(s);
        }
        return unicodeBytes.toString();     
    }
	
	
	/**
	 * 将字符串转换为Unicode编码
	 * @param str
	 * @return
	 * @author hcl
	 */
	public static String encryptUnicode(String str) {
		if(str == null)return null;
		if("".equals(str.trim())) return "";
        char[] utfBytes = str.toCharArray();
        StringBuilder unicodeBytes = new StringBuilder();
        for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
            unicodeBytes.append(encryptUnicode(utfBytes[byteIndex]));
        }
        return unicodeBytes.toString();     
    }
	
	
	
	/**
	 * 将一个char Unicode编码
	 * @param c
	 * @return
	 * @author hcl
	 */
	public static String encryptUnicode(char c){
		String hexB = Integer.toHexString(c);   //转换为16进制整型字符串  
        if (hexB.length() <= 2) {
            hexB = "00" + hexB;
        }
        return "\\u" + hexB;
	}
	

	/**
	 * 将字符串进行Unicode 解码
	 * @param dataStr
	 * @return
	 * @author hcl
	 */
    public static String decodeUnicode(String dataStr) {     
       int start = 0;     
       int end = 0;     
       StringBuilder buffer = new StringBuilder();     
       while (start > -1) { 
    	   int tempStart = 0;
    	   tempStart = dataStr.indexOf("\\u", start);
           String charStr = "";     
           if (tempStart == -1) {     
               charStr = dataStr.substring(start, dataStr.length());
               end = -1;
           } else {
        	   start = tempStart;
        	   if(end != start){
        		   buffer.append(dataStr.substring(end, start));  
        	   }
        	   end = start + 6;
               charStr = dataStr.substring(start + 2, end);     
               char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。     
               charStr = new Character(letter).toString();
           }     
           
           buffer.append(charStr);  
           start = end;
       }     
       return buffer.toString();     
    }  
	
	
}
